package com.example.demo.exception;

import com.example.demo.utils.BSResultUtils;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class BSExceptionHandler {



    public boolean isAjax(HttpServletRequest request){

        return (request.getHeader("x-requested-with")!=null && "XMLHttpRequest".equals(request.getHeader("x-requested-with").toString()));

    }



      @ExceptionHandler(value = Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Object handle500(HttpServletRequest request,Model model,Exception e){


        e.printStackTrace();
        if(!isAjax(request)){

            return BSResultUtils.build(500,e.getMessage(),null);
        }


        model.addAttribute("url",request.getRequestURL());
        model.addAttribute("exception","系统繁忙，请稍候再试");
        return "exception";
    }





}
